package ex.algorithms.datastructures;

public class LinkedList {
	private LinkedListItem head;
	
	public void insert(LinkedListItem item) {
		if(head == null) {
			head = item;
			return;
		}
		
		head.setPrev(item);
		item.setNext(head);
		
		head = item;
	}
	
	public void append(LinkedListItem item) {
		if(head == null) {
			head = item;
			return;
		}
		
		LinkedListItem tmpHead = head;
		while(tmpHead.getNext() != null)
			tmpHead = tmpHead.getNext();
		
		tmpHead.setNext(item);
		item.setPrev(tmpHead);
	}
	
	public LinkedListItem search(int value) {
		LinkedListItem tmpHead = head;
		while(tmpHead != null && tmpHead.getValue() != value)
			tmpHead = tmpHead.getNext();
		
		return tmpHead;
	}
	
	public void delete(LinkedListItem item) {
		if(item == null)
			return;
		
		if(item.getPrev() == null) {
			head = item.getNext();
			return;
		}
		
		if(item.getNext() == null) {
			item.getPrev().setNext(null);
			return;
		}
		
		item.getPrev().setNext(item.getNext());
	}
	
	public void print() {
		if(head == null) {
			System.out.println("Empty");
			return;
		}
		
		LinkedListItem tmpHead = head;
		while(tmpHead != null) {
			System.out.println(tmpHead.getValue());
			tmpHead = tmpHead.getNext();
		}
	}
}
